<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Response;
use App\Http\Requests\AdsUpdateRequest;
use App\Models\Position;
use App\Models\PositionTranslation;
use App\Services\QiniuServices;
use DB;


class AdsController extends AdminController
{
	private $sid;
	
    public function __construct()
    {
       parent::__construct();
	   
 
    }
	
    public function index()
    {
        return view('admin.ads.index');
    }

    public function data(Request $request)
    {
        $lang = $request->lang??lang();
        $model = PositionTranslation::query();
        $model = $model->where('locale',$lang);
		$keyword=$request->get('title');
        if ($keyword) {
			
            $model = $model->where('title', 'like',"%{$keyword}%")->orWhere('firsttitle', 'like', "%{$keyword}%");
        }


        $res = $model->with('advname')->where('pid','!=',0)->where('type',2)->orderBy('id', 'desc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return response()->json($data);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ads.create', compact('positions'));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createPosition()
    {
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ads.position', compact('positions'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(AdsUpdateRequest $request)
    {


         
        $data = $request->all();
        $request = (object)$data;
        DB::beginTransaction();
       // try {

            $Position = new Position();
            $Position->classname = $request->title;
            $Position->status = 1;
            $this->sid = PositionTranslation::max('sid');
            foreach (config('translatable.locales') as $locale => $item) {
			  $Position->translateOrNew($locale)->sid = $this->sid + 1;	
              $Position = $this->createItem($Position,$request,$locale);
            }
            $Position->save();
            DB::commit();

            return Response::json(['code' => 0, 'msg' => '添加成功', 'data' => '添加成功', 'url' => route('admin.ads')]);

       // } catch (\Exception $exception) {
            DB::rollback();

       // }


        return response()->json(['code' => 0, 'msg' => '系统错误']);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function editPosition(Request $request)
    {
        $id = (int)$request->get('id');
        $position = PositionTranslation::with('advname')->findOrFail($id);
        $position = $position->advname;
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ads.positionedit', compact('positions', 'position','id'));
    }



    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request)
    {
        $id = (int)$request->get('id');
        $position = PositionTranslation::with('advname')->findOrFail($id);
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ads.edit', compact('positions', 'position'));
    }





    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(AdsUpdateRequest $request)
    {

            $id = (int)$request->get('id');
            if(empty($id))  return Response::json(['code' => 1, 'msg' => '非法操作']);
            $data = $request->except(['_token', 'file']);
			$request = (object)$data;
            $PositionTranslation = PositionTranslation::findOrFail($id);
            
            $Position = Position::whereTranslation('id', $id)->firstOrFail();
			$Position->classname = $request->title;
			
			DB::beginTransaction();
			try { 
			 
				foreach (config('translatable.locales') as $locale => $item) {
					
					if(!$Position->hasTranslation($locale)){
						$Position = $this->createItem($Position,$request,$locale);
						$Position->translateOrNew($locale)->sid = $PositionTranslation->sid;
						$Position->translateOrNew($locale)->pid = $PositionTranslation->pid;
					}
						
						
					
				}

				if($Position->save() && $PositionTranslation->update($data)){
					DB::commit();
				}
				return response()->json(['code' => 0, 'msg' => '更新成功']);
			} catch (\Exception $exception) {
				DB::rollback();
			}
       
           
        
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,QiniuServices $qiniu)
    {
        $ids = (array)$request->get('ids');
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
		
        DB::beginTransaction();
        try { 
		
		
			//删除云端资源
			foreach($ids as $id){
				
				//检查广告位下是否有 广告
				$Position = Position::whereTranslation('id', $id)->firstOrFail();
				if($Position->translations->count()){
					foreach($Position->translations as $obj){
						//删除云端资源
						$qiniu->objFromDelete($obj);
					}
					$Position->deleteTranslations();
					
				}
				$Position->delete();
			}			

			DB::commit();
			return response()->json(['code' => 0, 'msg' => '删除成功']);
		
			
        } catch (\Exception $exception) {
            DB::rollback();
        }

        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }
  


	
	private function createItem($Position,$request,$locale){
		
			//新增时此时需要设置
 
			 
			$Position->translateOrNew($locale)->pid = $request->pid;
			$Position->translateOrNew($locale)->type = 2;
			$Position->translateOrNew($locale)->title = $request->title;
			$Position->translateOrNew($locale)->firsttitle = $request->firsttitle??'';
			$Position->translateOrNew($locale)->secondtitle = $request->secondtitle??'';
			$Position->translateOrNew($locale)->thirdtitle = $request->thirdtitle??'';
			$Position->translateOrNew($locale)->keywords = $request->keywords??'';
			$Position->translateOrNew($locale)->description = $request->description??'';
			$Position->translateOrNew($locale)->thumb = $request->thumb??'';
			$Position->translateOrNew($locale)->body = $request->body??'';
			$Position->translateOrNew($locale)->sort = $request->sort??255;
		return $Position;
	}
	
    /**
     * type:2  文字广告位
     *
     * @return array
     */
    private function getPositionClass(){
     return  PositionTranslation::lang()->where('pid',0)->where('type',2)->get();

    }

}
